import { darken, lighten, rgbToHex, setCssColorVariables } from '@/utils/color'
import { useAppStoreWithOut } from '@/store/modules/app'
import type { ThemeNames, CurrentTheme } from '@/store/modules/types/app'

const appStore = useAppStoreWithOut()

export const useTheme = () => {
  let currentTheme = appStore.getTheme

  // 预设定主题
  const themes: Record<ThemeNames, string> = {
    orangeRed: '#ff4500',
    darkOrange: '#ff8c00',
    gold: '#ffd700',
    lightGreen: '#90ee90',
    darkTurquoise: '#00ced1',
    dodgerBlue: '#1e90ff',
    mediumVioletRed: '#c71585',
    custom: ''
  }

  // 初始化主题
  const initTheme = () => {
    applyTheme(currentTheme.themeColor)
  }

  // 设置颜色
  const setThemeColor = (color: string) => {
    setCssColorVariables({
      '--el-color-primary': color,
      '--el-color-primary-light-2': lighten(color, 20),
      '--el-color-primary-light-3': lighten(color, 30),
      '--el-color-primary-light-5': lighten(color, 50),
      '--el-color-primary-light-7': lighten(color, 70),
      '--el-color-primary-light-8': lighten(color, 80),
      '--el-color-primary-light-9': lighten(color, 90),
      '--el-color-primary-dark-2': darken(color, 20)
    })
  }

  // 应用主题
  const applyTheme = (themeColor: string) => {
    const predefineThemes: [ThemeNames, string][] = Object.entries(themes).map(([key, value]) => [
      key as ThemeNames,
      value
    ])
    let themeName: ThemeNames = 'custom' // 主题名称
    for (let i = 0; i < predefineThemes.length; i++) {
      if (
        predefineThemes[i][1] === (themeColor.startsWith('#') ? themeColor : rgbToHex(themeColor))
      ) {
        themeName = predefineThemes[i][0]
        break
      }
    }

    currentTheme = { themeName, themeColor }

    // 设置 HTML 属性用于自定义样式
    document.documentElement.setAttribute('data-theme', themeName)

    appStore.setTheme(currentTheme)

    // 改变颜色
    setThemeColor(themeColor)

    // 触发主题变化事件
    dispatchThemeChange(currentTheme)
  }

  // 获取当前主题
  const getCurrentTheme = () => {
    return currentTheme
  }

  // 获取所有可用主题
  const getAvailableThemes = () => {
    return themes
  }

  // 分发主题变化事件
  const dispatchThemeChange = (themeName: CurrentTheme) => {
    const event = new CustomEvent('theme-change', {
      detail: { theme: themeName }
    })
    window.dispatchEvent(event)
  }

  // 监听主题变化
  const onThemeChange = (callback: any) => {
    window.addEventListener(
      'theme-change',
      (
        event: CustomEvent<{
          theme: CurrentTheme
        }>
      ) => {
        callback(event.detail.theme)
      }
    )
  }

  return {
    themes,
    initTheme,
    applyTheme,
    getCurrentTheme,
    getAvailableThemes,
    onThemeChange
  }
}
